//
//  WMAgentApi.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/5.
//

import UIKit
import Alamofire

let signStr: String = "qsy&&!!!,,@@?1227,,***."

enum ApiEnum {
    
    case startUp(_ params: [String: Any])
    case eventSave(_ params: [String: Any])
    case verifyCode(_ p: String)
    case feedback(_ content: String)
    case myFuncList
    case logout
    case phoneLogin(_ p: String, _ code: String)
    case wechatLogic(_ code: String)
    case oneclickLogin(_ token: String, _ accessToken: String)
    case productList
    case subscribeVerify(_ receipt: String)
    case appleLogic(_ token: String, _ userId: String)
    case parseVideo(_ url: String)
    case permission

    var url: String {
        return domain + path
    }
    
    var params: [String : Any]? {
        switch self {
        case .startUp(let params):
            return params
        case .eventSave(let params):
            return params
        case .verifyCode(let p):
            return ["p": p.base64Encoded]
        case .feedback(let content):
            return ["content": content, "udid": getUUID(), "userId": UserDefaults.standard.value(forKey: UserDefaultsKey.loginUserId) ?? 0]
        case .myFuncList:
            return ["sysOs": "iOS"]
        case .phoneLogin(let p, let code):
            return ["p": p.base64Encoded, "code": code, "udid": getUUID(), "sysOs": "iOS"]
        case .wechatLogic(let code):
            return ["code": code]
        case .subscribeVerify(let receipt):
            return ["receipt": receipt]
        case .oneclickLogin(let token, let accessToken):
            return ["token": token, "accessToken": accessToken]
        case .appleLogic(let token, let userId):
            return ["identityToken": token, "appleUserid": userId]
        case .parseVideo(let url):
            return ["url": url]
        case .permission:
            return ["udid": getUUID()]
        default:
            return nil
        }
    }

    var path: String {
        switch self {
        case .startUp:
            return "start/up"
        case .eventSave:
            return "event/save"
        case .verifyCode:
            return "user/vcode"
        case .feedback:
            return "lmessage/leaveMessage"
        case .myFuncList:
            return "user/myInfo"
        case .logout:
            return "user/cancel"
        case .phoneLogin:
            return "user/vlogin"
        case .wechatLogic:
            return "user/wxlogin"
        case .oneclickLogin:
            return "user/oneclick"
        case .productList:
            return "paylist/ios"
        case .appleLogic:
            return "user/applelogin"
        case .subscribeVerify:
            return "apple/subscribe"
        case .parseVideo:
            return "parse/video"
        case .permission:
            return "parse/free"
        }
    }
    
    var method: HTTPMethod {
        switch self {
        case .productList, .myFuncList:
            return .get
        default:
            return .post
        }
    }
    
    var domain: String {

        if let dimain = UserDefaults.standard.value(forKey: UserDefaultsKey.domain) as? String, !dimain.isEmpty {
            return dimain
        }
        return "https://dkqsyapi.awaketec.com/"
    }

    var headers: [String : String] {
        var h: [String: String] = [:]
        h["u_sysOS"] = "iOS"
        h["u_version"] = AppInfo.appVersion
        h["e_efrom"] = "wydsios"
        h["u_efrom"] = "wydsios"
        h["u_udid"] = getUUID()
        let time = Int(NSDate().timeIntervalSince1970 * 1000).description
        h["u_timestamp"] = time
        let sign = "udid=\(getUUID())&timestamp=\(time)&\(signStr)"
        h["u_sign"] = sign.md5.lowercased()
        h["u_userId"] = (UserDefaults.standard.value(forKey: UserDefaultsKey.loginUserId) as? Int ?? 0).description
        h["token"] = (UserDefaults.standard.value(forKey: UserDefaultsKey.loginUserToken) as? String ?? "")
        switch self {
        case .eventSave:
            h["Content-Type"] = "application/json"
        default:
            break
        }

        return h
    }
    
}

class WMAgentApi: NSObject {
 
    static let shared = WMAgentApi()
    
    let manager: Session!

    private override init() {
        let configuration = URLSessionConfiguration.default
        configuration.httpMaximumConnectionsPerHost = 50
        configuration.timeoutIntervalForRequest = 30
        manager = Alamofire.Session(configuration: configuration)
    }

    // 普通get、post请求
    func requestApi(_ api: ApiEnum, response: (([String: Any]) -> Void)? = nil) {
        let haveNet = UserDefaults.standard.value(forKey: UserDefaultsKey.haveNetwork) as? Int ?? 0
        if haveNet == 0 {
            return;
        }
        manager.request(api.url, method: api.method, parameters: api.params ?? [:], headers: HTTPHeaders(api.headers)).responseJSON(queue: .global(qos: .utility )) { res in
            if let data = res.value as? [String: Any] {
                Async.main {
                    response?(data)
                }
            }
        }
    }

    // raw请求方式
    func requestRaw(_ api: ApiEnum, response: (([String: Any]) -> Void)? = nil) {
        let haveNet = UserDefaults.standard.value(forKey: UserDefaultsKey.haveNetwork) as? Int ?? 0
        if haveNet == 0 {
            return;
        }
        let data = try? JSONSerialization.data(withJSONObject: api.params ?? [:], options: [])
        var request = URLRequest(url: URL(string: api.url)!)
        request.httpMethod = api.method.rawValue
        request.httpBody = data
        request.allHTTPHeaderFields = api.headers
        manager.request(request).responseJSON(queue: .global(qos: .utility )) { res in
            if let data = res.value as? [String: Any] {
                Async.main {
                    response?(data)
                }
            }
        }
    }
    
    // 文件上传
    func requestUploadFile(_ api: ApiEnum, fileData: [String: Data], response: (([String: Any]) -> Void)? = nil) {
        manager.upload(multipartFormData: { formatData in
            for (key, value) in (api.params ?? [:]) {
                formatData.append("\(value)".data(using: .utf8)!, withName: key)
            }
            for type in fileData.keys {
                formatData.append(fileData[type]!, withName: type, fileName: "\(type).png", mimeType: "image")
            }
        }, to: api.url, method: api.method, headers: HTTPHeaders(api.headers)).responseJSON(queue: .global(qos: .utility )) { res in
            let data = res.value as? [String: Any] ?? [:]
            Async.main {
                response?(data)
            }
        }
    }
    

}
 
